<template>
  <div>
    <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible" fullscreen
      center>
      <el-button class="miui-dialog-close-btn" @click="visible = false">关闭页面</el-button>
      <el-divider content-position="left">单据信息</el-divider>
      <el-form :model="dataForm" ref="dataForm" label-width="90px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="单据日期" prop="createTime">
              <el-input v-model="dataForm.createTime" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库类型">
              <el-input :v-model="dataForm.inveType" value="其他入库" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制造商">
              <el-input v-model="dataForm.supplyName" v-if="!dataForm.id">
                <el-button slot="append" @click="openDialog('supply')">选择</el-button>
              </el-input>
              <el-select v-model="dataForm.supplyId" v-if="dataForm.id" disabled>
                <el-option v-for="item in supplyOptions" :value="item.id" :label="item.name" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="收入仓位">
              <el-select size="mini" v-model="dataForm.inStockId">
                <el-option v-for="item in stockOptions" :value="item.id" :label="item.name" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制单人" prop="createUserName">
              <el-input v-model="dataForm.createUserName" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="memo">
              <el-input v-model="dataForm.memo"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form :inline="true">
            <el-form-item>
              <el-button type="primary" @click="addGoodsBySingle">单品添加商品</el-button>
            </el-form-item>
            <el-form-item style="float: right;">
              <el-button type="danger" @click="delTableData">删除</el-button>
            </el-form-item>
          </el-form>
        </el-row>
      </el-form>

      <el-divider content-position="left">商品信息</el-divider>

      <div class="avue-crud">
        <el-table :data="dataList" border v-loading="dataListLoading" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="goodsCode" label="商品代码"></el-table-column>
          <el-table-column prop="goodsName" label="商品名称"></el-table-column>
          <el-table-column prop="spec" label="型号" width="80"></el-table-column>
          <el-table-column prop="unitType" label="计量单位" width="80" :formatter="unitTypeFormatter"></el-table-column>
          <el-table-column prop="auditTime" label="入库时间"></el-table-column>
          <el-table-column prop="goodsBarcode" label="商品条码"></el-table-column>
          <el-table-column prop="quantity" label="数量" width="60">
            <template slot-scope="scope">
              <el-input v-model="scope.row.quantity" :ref="'number'+scope.$index" @keyup.enter.native="enterChange(scope.$index)"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit" :loading="ischeck" v-prevent-re-click>保存</el-button>
        <el-tooltip :content="'isAudit: ' + dataForm.isAudit" placement="top">
          <el-switch v-model="dataForm.isAudit" active-text="保存并审核" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0">
          </el-switch>
        </el-tooltip>
      </span>

      <!-- 商品信息 -->
      <goods-search-single v-if="goodsVisible" ref="goodsDialog" @updateForm="updateFormData"></goods-search-single>
      <search-supply v-if="supplyVisible" ref="supplyDialog" @refreshData="getSupplyId"></search-supply>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getInfoById,
    insertOtherPutStorage,
    editOtherPutStorageInfo
  } from "@/api/eims/purchase/other-warehouse"
  import { mapGetters } from "vuex"
  import {
    getStockList,
    getStockInfo
  } from "@/api/eims/stock"
  import {
    timeCompute,
    timeString
  } from "@/util/tools"
  import GoodsSearchSingle from '@/components/business/goods-search-single'
  import SearchSupply from './supply-search'
  import {
    getSupplyListByIds
  } from "@/api/eims/supply"

  export default {
    data() {
      return {
        ischeck: false,
        dataListLoading: false,
        visible: false,
        dataForm: {
          id: 0,
          detailList: [],
          inStockId: '',
          inveType: 'OTI',
          memo: "",
          isAudit: "",
          supplyName: '',
          supplyId: ''
        },
        stockOptions: [],
        supplyOptions: [],
        dataList: [],
        goodsVisible: false,
        supplyVisible: false,
      };
    },
    created() {
      this.getStockListInfo()
    },
    computed: {
      ...mapGetters(["userInfo"])
    },
    components: {
      GoodsSearchSingle,
      SearchSupply
    },
    methods: {
      init(id) {
        this.dataForm.id = id || 0;
        this.visible = true
        this.dataForm.inStockId = ''
        this.dataForm.supplyName = ''
        this.dataForm.supplyId = ''
        this.dataForm.isAudit = 0
        this.dataForm.createTime = timeCompute(new Date())
        this.dataForm.createUserName = this.userInfo.realName
        this.dataForm.detailList = []
        this.dataList = []
        this.$nextTick(() => {
          this.$refs["dataForm"].resetFields();
          if (this.dataForm.id) {
            getInfoById(this.dataForm.id).then(response => {
              if(response.data.code == '0'){
                this.dataForm = response.data.data
                this.dataList = response.data.data.detailList
                this.getSupplyList(this.dataForm.supplyId)
              }else{
                this.$message.error(response.data.msg)
              }
            })
          }
        })
      },

      // 打开商品列表弹窗
      addGoodsBySingle() {
        if (!this.dataForm.supplyId) {
          this.$message.warning("请选择制造商");
          return;
        }
        if (this.dataForm.inStockId) {
          let params = {
            supplyId: this.dataForm.supplyId,
            supplyName: this.dataForm.supplyName,
            ctgId: 7,
            ctgName: '耗材'
          };
          let data = {
            params: params,
            data: this.dataList,
            disable: true
          };
          this.goodsVisible = true;
          this.$nextTick(() => {
            this.$refs.goodsDialog.init(data);
          });
        } else {
          this.$message.warning("请选择收入仓位");
        }
      },

      handleSelectionChange(val) {
        this.selectionList = val;
      },
      // 删除选中的商品
      delTableData() {
        let data = this.selectionList;
        data.forEach(item => {
          this.dataList.splice(item, 1);
        });
      },
      //  回车切换下一行商品数量
      enterChange(index){
        if(this.$refs['number'+(index*1 + 1)]){
          this.$refs['number'+(index*1 + 1)].focus()
        }
      },
      //更新表单数据
      updateFormData(data) {
        this.dataList = [];
        data.forEach(item => {
          this.dataList.push({
            goodsId: item.goodsId,
            goodsCode: item.code,
            goodsName: item.viewGoodsName,
            spec: item.spec,
            unitType: item.unitType,
            goodsBarcode: item.barcode
          });
        });
      },
      //保存按钮
      dataFormSubmit() {
        if (this.dataList.length <= 0) {
          this.$message.warning("请选择商品");
          return;
        }
        for (let i = 0; i < this.dataList.length; i++) {
          if (!this.dataList[i].quantity || this.dataList[i].quantity <= 0) {
            this.$message.warning("请设置正确的商品数量,商品数量应大于0");
            return;
          }
        }
        this.dataForm.detailList = this.dataList;
        this.ischeck = true
        if (this.dataForm.id) {
          editOtherPutStorageInfo(this.dataForm).then(response => {
            if(response.data.code == '0'){
              this.$message.success('修改成功')
              this.visible = false
              this.$emit('refreshDataList')
            }else{
              this.$message.error(response.data.msg)
            }
            this.ischeck = false
          }).catch(() => {
            this.ischeck = false
          })
        } else {
          insertOtherPutStorage(this.dataForm).then(response => {
            if(response.data.code == '0'){
              this.$message.success('添加成功')
              this.visible = false
              this.$emit('refreshDataList')
            }else{
              this.$message.error(response.data.msg)
            }
            this.ischeck = false
          }).catch(() => {
            this.ischeck = false
          })
        }
      },
      //获取制造商
      openDialog() {
        let data = {
          ctgId: 7
        }
        this.supplyVisible = true
        this.$nextTick(() => {
          this.$refs.supplyDialog.init(data)
        })
      },
      getSupplyId(data) {
        this.$set(this.dataForm, 'supplyName', data.name)
        this.dataForm.supplyId = data.id
      },
      //获取制造商列表
      getSupplyList(id) {
        let data = {
          ids: [id]
        }
        getSupplyListByIds(data).then(response => {
          if(response.data.code == '0'){
            this.supplyOptions = response.data.data
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      //获取仓位
      getStockListInfo() {
        getStockList().then(response => {
          if(response.data.code == '0'){
            this.supplyOptions = response.data.data
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      unitTypeFormatter(row, column, cellValue, index) {
        switch (cellValue) {
          case '01':
            return '片'
            break;
          case '02':
            return '盒'
            break;
          case '03':
            return '副'
            break;
          case '04':
            return '瓶'
            break;
          case '05':
            return '张'
            break;
          case '06':
            return '把'
            break;
          case '07':
            return '个'
            break;
          case '08':
            return '只'
            break;
          case '09':
            return '套'
            break;
          case '10':
            return '天'
            break;
          case '11':
            return '包'
            break;
        }
      }
    }
  };
</script>
<style>
  .el-divider__text,
  .el-link {
    font-size: 18px;
  }
</style>
